﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.IO;
using System.IO.Compression;
using System.Diagnostics;
using System.Reflection;

namespace PPTHelper
{
    partial class PPTHelper
    {

        #region //http服务
        HttpServer http;
        private void HttpSvr()
        {
            http = new HttpServer(51526);
            //路由方法
            http.RouteFunc.Add("/", HttpRoot);
            http.RouteFunc.Add("/PPTHelper", HttpMain);
            http.RouteFunc.Add("/PPTHelper/Api", HttpApi);
            http.RouteFunc.Add("/PPTHelper/JsonData", HttpJsonData);
            http.RouteFunc.Add("/PPTHelper/Play", (req) => { Play(); return null; });
            http.RouteFunc.Add("/PPTHelper/Stop", (req) => { Stop(); return null; });
            http.RouteFunc.Add("/PPTHelper/First", (req) => { First(); return null; });
            http.RouteFunc.Add("/PPTHelper/Last", (req) => { Last(); return null; });
            http.RouteFunc.Add("/PPTHelper/Previous", (req) => { Previous(); return null; });
            http.RouteFunc.Add("/PPTHelper/Next", (req) => { Next(); return null; });
            http.RouteFunc.Add("/PPTHelper/Slides", HttpSlides);
            http.RouteFunc.Add("/PPTHelper/Screen", HttpGetScreen);
            http.RouteFunc.Add("/PPTHelper/Run", HttpRun);
            //启动http
            http.Start();
        }


        //Api列表
        [Description("#Api列表")]
        HttpResutl HttpApi(HttpListenerRequest req)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"<html><head></head><title>{PPTHelper.Title}</title><body>");
            sb.AppendLine("<br>HTTP服务</br>");
            foreach (var item in http.RouteFunc)
            {
                var desc = GetDescription(item.Value).Split('#');
                var ar = desc.Length > 0 ? $"{desc[0]}" : null;
                var rd = desc.Length > 1 ? $"{desc[1]}" : null;
                var link = $"{item.Key}{ar}";
                sb.AppendLine($"<a href='{link}'>{link}</a><span>    {rd}</span><br />");
            }
            sb.AppendLine("<br>Websocket服务</br>");
            foreach (var item in ActionFunc)
            {
                var desc = GetDescription(item.Value).Split('#');
                var ar = desc.Length > 0 ? $"{desc[0]}" : null;
                var rd = desc.Length > 1 ? $"{desc[1]}" : null;
                var link = $"{item.Key}{ar}";
                sb.AppendLine($"<a href='/PPTHelper/Run?command={link}'>{link}</a><span>    {rd}</span><br />");
            }
            sb.AppendLine("</body></html>");
            return new HttpResutl(sb.ToString())
            {
                Headers = new Dictionary<string, string>
                { { "content-type", "text/html; Charset=utf-8" } },
            };
        }


        //主页
        [Description("#读取Default.html文件，不存在则跳转到内置主页")]
        public HttpResutl HttpRoot(HttpListenerRequest arg)
        {
            var html = "<html><head><meta http-equiv='Refresh' content='0; URL=/PPTHelper' /></head></html>";
            var path = Path.Combine(AppContext.BaseDirectory, "Default.html");
            if (File.Exists(path)) html = File.ReadAllText(path);
            return new HttpResutl(html);
        }

        //内置主页
        [Description("#内置主页")]
        public HttpResutl HttpMain(HttpListenerRequest req)
        {
            var html = Properties.Resources.HTMLPage1;
            html = html.Replace("{{title}}", PPTHelper.Title);
            return new HttpResutl(html);
        }

        //json数据
        HttpResutl HttpJsonData(HttpListenerRequest req)
        {
            var data = GetData();
            var content = data.ToJson();
            return new HttpResutl(content)
            {
                Headers = new Dictionary<string, string>
                { { "content-type", "application/Json; Charset=utf-8" } },
            };
        }


        //PPT图片
        [Description("?page=1#PPT页面图片")]
        public HttpResutl HttpSlides(HttpListenerRequest req)
        {
            var page = req.QueryString.Get("page");
            if (int.TryParse(page, out int i))
            {
                var bytes = GetImage(i);
                return new HttpResutl(bytes)
                {
                    Headers = new Dictionary<string, string>
                    { { "content-type", "image/png" }, { "Cache-Control","no-cache"} }
                };
            }
            return null;
        }

        //屏幕图片
        [Description("?i=0#屏幕图片,屏幕号0-1")]
        public HttpResutl HttpGetScreen(HttpListenerRequest req)
        {
            var page = req.QueryString.Get("i");
            if (int.TryParse(page, out int i))
            {
                var bytes = PrintScreen.GetScreenImage(i);
                return new HttpResutl(bytes)
                {
                    Headers = new Dictionary<string, string>
                    {{ "content-type", "image/jpeg" } ,{ "Cache-Control","no-cache" }}
                };
            }
            return null;
        }

        #endregion

        //命令动作
        [Description("?command=MouseMove,0,100,100,1920,1080#内置命令,屏幕号,坐标x,坐标y,屏宽w,屏高h")]
        public HttpResutl HttpRun(HttpListenerRequest req)
        {
            var cmd = req.QueryString.Get("command");
            return WsMain(cmd);
        }


        /// <summary>
        /// 获取Description内容
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        string GetDescription(dynamic func)
        {
            if (func?.Method is MethodInfo method)
            {
                var attrs = method.GetCustomAttributes(typeof(DescriptionAttribute), false);
                var attr = attrs?.Select(a => ((DescriptionAttribute)a).Description);
                return attr != null ? string.Join(",", attr) : string.Empty;
            }
            return string.Empty;
        }


    }
}
